<?php

namespace app\common\controller;

use think\Controller;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Env;
use think\facade\Log;
use think\facade\Request;

class Common extends Controller
{
    private $config = null;
    private $root_path = null;
    protected $site_config = null;

    protected function initialize()
    {
        parent::initialize();
        $this->config = Config::pull("server");
        $this->root_path = Env::get('root_path');
        $this->initConfig();

        if (empty($this->site_config['categorys'])) {
            $this->assign("categorys",array());
        }else {
            $this->assign("categorys", $this->site_config['categorys']);
        }

        $this->assign("site_config",$this->site_config);
        $this->assign("page_type",strtolower($this->request->controller()));
    }

    protected function initConfig()
    {
        $site_config = Config::pull("site_config");
        $app_debug = Config::get("app_debug");
        if (!empty($site_config) && $app_debug == false) {
             $this->site_config = $site_config;
        } else {
            $data = curl_server("apiv2/siteconfig");
            if (!empty($data)) {
                $res = book_arr2file($this->root_path . 'config/site_config.php', $data['data']);
                if ($res) {
                    Log::info('初始化站点配置文件成功');
                }else {
                    Log::info('初始化站点配置文件失败');
                }
                $this->site_config = $data['data'];
            }
        }
        return $this->site_config;
    }

    /**
     * 获取分类
     * @param int $cid
     * @return array
     */
    public function getCategory($cid = 0) {
        $category = array(
            'id' => 0,
            'alias' => "",
            'name' => "暂无分类"
        );

        if (is_array($this->site_config['categorys'])) {
            foreach ($this->site_config['categorys'] as $item) {
                if ($item['id'] == $cid) {
                    $category = $item;
                }
            }
        }

        return $category;
    }

    /**
     * 站点SEO
     * @param string $seo_type 页面类型
     * @param array $param 参数
     * @throws
     */
    protected function site_seo($seo_type = "",$param = array())
    {
        $site_config = Config::pull("site_config");
        if (empty($site_config)) {
            $site_config = $this->initConfig();
        }

        $seo_config = $site_config['site_seo'];

        $site_title = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['site_title']));
        $keywords = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['site_keywords']));
        $description = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['site_description']));


        if ($seo_type == "home") { //详情

            if(!empty($seo_config['site_title'])){
                $site_title = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['site_title']));
            }
            if(!empty($seo_config['site_keywords'])){
                $keywords = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['site_keywords']));
            }
            if(!empty($seo_config['site_description'])){
                $description = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['site_description']));
            }

        }else if ($seo_type == "details") { //详情
            $item = $param['item'];

            if(!empty($seo_config['details_title'])){
                $site_title = trim(str_replace(array('{title}','{author}','{category_name}','{site_name}'), array($item['title'],$item['author'],$param['category_name'],$site_config['site_name']), $seo_config['details_title']));
            }
            if(!empty($seo_config['details_keywords'])){
                $keywords = trim(str_replace(array('{title}','{author}','{category_name}','{site_name}'), array($item['title'],$item['author'],$param['category_name'],$site_config['site_name']), $seo_config['details_keywords']));
            }
            if(!empty($seo_config['details_description'])){
                $description = trim(str_replace(array('{title}','{author}','{category_name}','{introduction}','{update_time}','{site_name}'), array($item['title'],$item['author'],$param['category_name'],$item['introduction'],date("Y-m-d H:i:s",$item['update_time']),$site_config['site_name']), $seo_config['details_description']));
            }


        }else if ($seo_type == "chapter") { //章节
            $article = $param['article'];
            $chapter = $param['chapter'];

            if(!empty($seo_config['chapter_title'])){
                $site_title = trim(str_replace(array('{site_name}','{title}','{author}','{category_name}','{chapter_title}'), array($site_config['site_name'],$article['title'],$article['author'],$param['category_name'],$chapter['title']), $seo_config['chapter_title']));
            }
            if(!empty($seo_config['chapter_keywords'])){
                $keywords = trim(str_replace(array('{site_name}','{title}','{author}','{category_name}','{chapter_title}'), array($site_config['site_name'],$article['title'],$article['author'],$param['category_name'],$chapter['title']), $seo_config['chapter_keywords']));
            }
            if(!empty($seo_config['chapter_description'])){
                $description = trim(str_replace(array('{site_name}','{title}','{author}','{category_name}','{introduction}','{update_time}','{chapter_title}'), array($site_config['site_name'],$article['title'],$article['author'],$param['category_name'],$article['introduction'],date("Y-m-d H:i:s",$article['update_time']),$chapter['title']), $seo_config['chapter_description']));
            }

        }else if ($seo_type == "category") { //分类seo

            if(!empty($seo_config['category_title'])){
                $site_title = trim(str_replace(array('{category_name}','{site_name}'), array($param['category_name'],$site_config['site_name']), $seo_config['category_title']));
            }
            if(!empty($seo_config['category_keywords'])){
                $keywords = trim(str_replace(array('{category_name}','{site_name}'), array($param['category_name'],$site_config['site_name']), $seo_config['category_keywords']));
            }
            if(!empty($seo_config['category_description'])){
                $description = trim(str_replace(array('{category_name}','{site_name}'), array($param['category_name'],$site_config['site_name']), $seo_config['category_description']));
            }

        }else if ($seo_type == 'author'){ //作者seo
            if(!empty($seo_config['author_title'])){
                $site_title = trim(str_replace(array('{site_name}','{author}'), array($site_config['site_name'],$param['author']), $seo_config['author_title']));
            }
            if(!empty($seo_config['author_keywords'])){
                $keywords = trim(str_replace(array('{site_name}','{author}'), array($site_config['site_name'],$param['author']), $seo_config['author_keywords']));
            }
            if(!empty($seo_config['author_description'])){
                $description = trim(str_replace(array('{site_name}','{author}'), array($site_config['site_name'],$param['author']), $seo_config['author_description']));
            }
        }else if ($seo_type == 'search'){ //搜索seo
            if(!empty($seo_config['search_title'])){
                $site_title = trim(str_replace(array('{site_name}','{keyword}'), array($site_config['site_name'],$param['keyword']), $seo_config['search_title']));
            }
            if(!empty($seo_config['search_keywords'])){
                $keywords = trim(str_replace(array('{site_name}','{keyword}'), array($site_config['site_name'],$param['keyword']), $seo_config['search_keywords']));
            }
            if(!empty($seo_config['search_description'])){
                $description = trim(str_replace(array('{site_name}','{keyword}'), array($site_config['site_name'],$param['keyword']), $seo_config['search_description']));
            }
        }else if ($seo_type == 'news_detail'){ //资讯详情
            if(!empty($seo_config['news_details_title'])){
                $site_title = trim(str_replace(array('{site_name}','{title}','{chapter_title}'), array($site_config['site_name'],$param['title'],$param['chapter_title']), $seo_config['news_details_title']));
            }
            if(!empty($seo_config['news_details_keywords'])){
                $keywords = trim(str_replace(array('{site_name}','{title}','{chapter_title}'), array($site_config['site_name'],$param['title'],$param['chapter_title']), $seo_config['news_details_keywords']));
            }
            if(!empty($seo_config['news_details_description'])){
                $description = trim(str_replace(array('{site_name}','{title}','{chapter_title}','{introduction}'), array($site_config['site_name'],$param['title'],$param['chapter_title'],$param['introduction']), $seo_config['news_details_description']));
            }
        }else if ($seo_type == 'news_list'){ //资讯分类
            if(!empty($seo_config['news_list_title'])){
                $site_title = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['news_list_title']));
            }
            if(!empty($seo_config['news_list_keywords'])){
                $keywords = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['news_list_keywords']));
            }
            if(!empty($seo_config['news_list_description'])){
                $description = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['news_list_description']));
            }
        }else if ($seo_type == 'special_list'){ //专辑分类
            if(!empty($seo_config['special_list_title'])){
                $site_title = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['special_list_title']));
            }
            if(!empty($seo_config['special_list_keywords'])){
                $keywords = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['special_list_keywords']));
            }
            if(!empty($seo_config['special_list_description'])){
                $description = trim(str_replace(array('{site_name}'), array($site_config['site_name']), $seo_config['special_list_description']));
            }
        }else if ($seo_type == 'special_detail'){ //专辑详情
            if(!empty($seo_config['special_details_title'])){
                $site_title = trim(str_replace(array('{site_name}','{title}'), array($site_config['site_name'],$param['title']), $seo_config['special_details_title']));
            }
            if(!empty($seo_config['special_details_keywords'])){
                $keywords = trim(str_replace(array('{site_name}','{title}'), array($site_config['site_name'],$param['title']), $seo_config['special_details_keywords']));
            }
            if(!empty($seo_config['special_details_description'])){
                $description = trim(str_replace(array('{site_name}','{title}','{introduction}'), array($site_config['site_name'],$param['title'],$param['introduction']), $seo_config['special_details_description']));
            }
        }


        $site_seo = array(
            'title' =>  $site_title,
            'keywords' =>   $keywords,
            'description' =>   $description,
        );

        $this->assign('site_seo', $site_seo);
    }

    /**
     * 获取模板
     * @param string $template 模板名称
     * @param array $vars 模板参数
     * @param array $config
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $config = [])
    {
        $domain = str_replace(array('https://','http://'),'',Request::domain());
        $domain = explode('.',$domain);
        if (is_array($domain) && $domain[0] == 'm') {
            $template .= '_m';
        }
        return parent::fetch($template, $vars, $config);
    }


    /**
     * 生成静态
     * @param string $htmlFile 文件名称
     * @param string $htmlPath 文件路径
     * @param string $templateFile 模板文件
     * @return bool
     */
    protected function buildHtml($htmlFile='',$htmlPath='',$templateFile='') {
        $content    =   $this->fetch($templateFile);
        $htmlPath   =   !empty($htmlPath) ? $htmlPath : Env::get('root_path') . '/public/'; // 项目目录下的html目录
        $htmlFile   =   $htmlPath.$htmlFile.'.html';
        $dir   =  dirname($htmlFile);
        if(!is_dir($dir)){
            mkdir($dir,0777,true);
        }
        if(file_put_contents($htmlFile,$content) === false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * json输出
     * @param string $data
     * @param string $msg
     * @param int $code
     */
    protected function ajaxJson ($data = '',$msg = '获取成功',$code = 0) {
      $data = json_encode(array('data' => $data,'msg' => $msg,'code' => $code));
      header('Content-Type:application/json; charset=utf-8');
      exit($data);
    }

}
